package main

import (
	"fmt"
	"io"
	"net"
	"sync"
)

type Server struct {
	Ip        string
	Port      int
	OnlineMap map[string]*User
	mapLock   sync.RWMutex
	Message   chan string
}

func NewServer(ip string, port int) *Server {
	server := &Server{
		Ip:        ip,
		Port:      port,
		OnlineMap: make(map[string]*User),
		Message:   make(chan string),
	}
	return server
}

//监听广播消息并发送
func (this *Server) ListenMessage() {
	for {
		msg := <-this.Message
		this.mapLock.Lock()
		for _, cli := range this.OnlineMap {
			cli.C <- msg
		}
		this.mapLock.Unlock()
	}
}

//发送广播消息
func (this *Server) BroadCast(user *User, msg string) {
	sendMsg := "[" + user.Addr + "]" + user.Name + ":" + msg

	this.Message <- sendMsg
}

//处理连接句柄
func (this *Server) Handler(conn net.Conn) {
	//连接成功
	//按连接生成用户
	user := NewUser(conn, this)
	user.Online()

	//接收用户消息
	go func() {
		buf := make([]byte, 4096)
		for {
			n, err := conn.Read(buf)
			if n == 0 {
				user.Offline()
				return
			}
			if err != nil && err != io.EOF {
				fmt.Println("conn read 错误:", err)
				return
			}
			msg := string(buf[:n-1]) //去掉回车
			// 处理消息
			user.DealMsg(msg)
		}
	}()
}

func (this *Server) Start() {
	//监听端口
	listener, err := net.Listen("tcp", fmt.Sprintf("%s:%d", this.Ip, this.Port))
	if err != nil {
		fmt.Println("listen err:", err)
		return
	}
	// 析构时关闭连接
	defer listener.Close()

	// 监听广播消息
	go this.ListenMessage()

	for {
		//连接
		conn, err := listener.Accept()
		if err != nil {
			fmt.Println("Accept err:", err)
			continue
		}
		//连接成功,处理连接
		go this.Handler(conn)
	}
}
